/**
* AutoSWF - Cody Cushing. March 26, 2009
* Copyright (c) 2009 Cody Cushing
* No use restrictions. Maintain this notice in all versions. 
**/

package com.autoswf.dispatcher
{
	import com.autoswf.core.Link;
	import com.autoswf.core.Transport;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;


	/**
	 * Allows events passed up or down the chain to be dispatched.
	 */
	public class LinkDispatcher extends Link implements IEventDispatcher
	{
		protected var _dispatcher:EventDispatcher;
		
		
		/**
		 * Constructor.
		 */
		public function LinkDispatcher(id:String)
		{
			super(id);
			
			_dispatcher = new EventDispatcher();
		}
		
		
		/** If the transport object is an event, dispatch it before passing it up. */
		override public function sendUp(object:*):void
		{
			var transport:Transport = (object is Transport) ? object : new Transport(object);
			
			if(transport.message is Event)
			{
				var event:Event = transport.message;
				_dispatcher.dispatchEvent(event);
			}
			
			notifyParents(transport);
		}
		
		
		/** If the transport object is an event, dispatch it before passing it down. */
		override public function sendDown(object:*):Object
		{
			var transport:Transport = Transport(object);
			if(transport.message is Event)
			{
				var event:Event = transport.message;
				_dispatcher.dispatchEvent(event);
			}
			
			return super.sendDown(transport);
		}

		
		/* IEventDispatcher methods */
		public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
		{
			_dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference)
		}
		
		public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void
		{
			_dispatcher.removeEventListener(type, listener, useCapture);
		}
		
		public function dispatchEvent(event:Event):Boolean
		{
			return _dispatcher.dispatchEvent(event);
		}
		
		public function hasEventListener(type:String):Boolean
		{
			return _dispatcher.hasEventListener(type);
		}
		
		public function willTrigger(type:String):Boolean
		{
			return _dispatcher.willTrigger(type);
		}
		
	}
}